package org.dbutils.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.dbutils.dao.StaffDao;
import org.dbutils.entity.StaffEntity;
import org.dbutils.util.DruidUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @AUTHOR CJ
 * <p>
 * *@DATE 2025 - 02 - 26
 */
public class StaffDaoImplDbUtills implements StaffDao {
    QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());


    @Override
    public StaffEntity selectById(int id) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs where id=?" ;
        try {
            return qr.query(sql,new BeanHandler<>(StaffEntity.class),id);
        } catch (SQLException e) {
            throw new RuntimeException("根据ID查询异常",e);
        }
    }

    @Override
    public List<StaffEntity> selectByPage(int currentPage, int pageSize) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs limit ?,?" ;
        int limit = (currentPage-1) * pageSize ;
        BeanListHandler<StaffEntity> beanListHandler =
                new BeanListHandler<>(StaffEntity.class) ;
        try {
            return qr.query(sql,beanListHandler,limit,pageSize) ;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(StaffEntity staff) {
        String sql = "update `staffs` set name = ?,age = ?,phone = ?,sta_pos = ? where id = ?";
        Object[] params = {staff.getName(), staff.getAge(), staff.getPhone(), staff.getStaPos(),staff.getId()};
        try {
            return qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public int deleteStaff(int id) {
        String sql = "delete from `staffs` where id =?";
        try {
            return qr.update(sql, id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public int insertStaff(StaffEntity staff) {
        String sql = "insert into staffs(name,age,phone,sta_pos) values (?,?,?,?)";
        Object[] params = {staff.getName(), staff.getAge(), staff.getPhone(), staff.getStaPos()};
        try {
            return qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
